diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1323a9e..c087ba1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,10 @@ this project adheres to [Semantic Versioning](https://semver.org/).
formatter that understands named arguments.
- `{l:LocalizeEnum}` re-resolves on every change of `ILocalizer.RefreshTriggeringRevision`, and so does
`LocalizeEnumConverter` with its new refresh-trigger child.
+- The opt-in package `ResXLocalization.MessageFormat`: ICU MessageFormat (`plural`, `select`) through
+ `Localizer.Current.UseMessageFormat()`, which parses every resolved value as an ICU message, with or
+ without arguments, optionally with a configured `MessageFormatter` of the `MessageFormat` library. See
+ [ICU MessageFormat](docs/guides/message-format.md).
### Changed
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 1678855..21248f4 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -12,6 +12,8 @@
+
+
diff --git a/ResXLocalization.NonWindows.slnf b/ResXLocalization.NonWindows.slnf
index a375d13..bbdb2b1 100644
--- a/ResXLocalization.NonWindows.slnf
+++ b/ResXLocalization.NonWindows.slnf
@@ -3,11 +3,13 @@
"path": "ResXLocalization.slnx",
"projects": [
"src\\ResXLocalization.Core\\ResXLocalization.Core.csproj",
+ "src\\ResXLocalization.MessageFormat\\ResXLocalization.MessageFormat.csproj",
"src\\ResXLocalization.SourceGenerators\\ResXLocalization.SourceGenerators.csproj",
"src\\ResXLocalization.Avalonia\\ResXLocalization.Avalonia.csproj",
"samples\\ResXLocalization.Avalonia.Sample\\ResXLocalization.Avalonia.Sample.csproj",
"tests\\ResXLocalization.Avalonia.Sample.Tests\\ResXLocalization.Avalonia.Sample.Tests.csproj",
"tests\\ResXLocalization.Core.Tests\\ResXLocalization.Core.Tests.csproj",
+ "tests\\ResXLocalization.MessageFormat.Tests\\ResXLocalization.MessageFormat.Tests.csproj",
"tests\\ResXLocalization.SourceGenerators.Tests\\ResXLocalization.SourceGenerators.Tests.csproj"
]
}
diff --git a/ResXLocalization.slnx b/ResXLocalization.slnx
index d68cfce..57df655 100644
--- a/ResXLocalization.slnx
+++ b/ResXLocalization.slnx
@@ -2,6 +2,7 @@
+
@@ -12,6 +13,7 @@
+
diff --git a/docs/guides/enums.md b/docs/guides/enums.md
index 8109723..b8b39ac 100644
--- a/docs/guides/enums.md
+++ b/docs/guides/enums.md
@@ -81,6 +81,9 @@ explicitly:
Under the default formatter, a text that needs a plural - `1 file` and `3 files` - needs one enum
member per plural case: the default formatter is `string.Format` and does not choose between forms.
+With the ICU MessageFormat formatter of the `ResXLocalization.MessageFormat` package, one member and a
+`plural` pattern suffice, for example `{0, plural, one {# file} other {# files}}`; see
+[ICU MessageFormat](message-format.md).
## Where a markup extension is not accepted: `LocalizeEnumConverter`
diff --git a/docs/guides/format-arguments.md b/docs/guides/format-arguments.md
index 6141c94..a36984e 100644
--- a/docs/guides/format-arguments.md
+++ b/docs/guides/format-arguments.md
@@ -50,8 +50,9 @@ the same, so a custom formatter reads `Position`.
**Names matter only to a formatter that understands them.** The default `string.Format` formatter
ignores names and uses positions, so `MessageArguments.FromObject(new { Count = 1.5, Where = "x" })` fills `{0}` and `{1}`
-exactly like `MessageArguments.FromValues(1.5, "x")`. A formatter that knows names (ICU MessageFormat) finds a named
-argument both under its position and under its name.
+exactly like `MessageArguments.FromValues(1.5, "x")`. The ICU MessageFormat formatter of the
+`ResXLocalization.MessageFormat` package finds a named argument both under its position and under its name;
+see [ICU MessageFormat](message-format.md).
## In XAML
@@ -114,8 +115,9 @@ Localizer.Current.Get("FilePosition", MessageArguments.FromTuples((null, index),
Both become `MessageArgument`s - a position, an optional name and the resolved value - which is what a
custom formatter receives. The position of an `` is its index among the children, whether it
has a name or not; the default formatter ignores names, so `File {0} of {1}` renders `File 3 of 10`
-for `Index` 3 and `Count` 10. A formatter that understands names (ICU MessageFormat) finds a named
-argument under its name too.
+for `Index` 3 and `Count` 10. The ICU MessageFormat formatter of the `ResXLocalization.MessageFormat`
+package finds a named argument under its name too, so `File {0} of {Total}` works there; see
+[ICU MessageFormat](message-format.md).
## Worth knowing
@@ -181,5 +183,7 @@ argument under its name too.
```
- **Keep it simple.** For a very complex string, compose the text in the view model with
`Get(key, MessageArguments.FromValues(…))` rather than writing many `` elements.
-- **Composite formatting does not pluralize.** `1 people invited` is on the resource author; use
- separate singular and plural resources where it matters.
+- **Composite formatting does not pluralize.** Under the default formatter, `1 people invited` is on the
+ resource author; use separate singular and plural resources where it matters, or install the ICU
+ MessageFormat formatter of the `ResXLocalization.MessageFormat` package, whose `plural` chooses the form
+ by the count: see [ICU MessageFormat](message-format.md).
diff --git a/docs/guides/message-format.md b/docs/guides/message-format.md
new file mode 100644
index 0000000..02a46ee
--- /dev/null
+++ b/docs/guides/message-format.md
@@ -0,0 +1,432 @@
+# ICU MessageFormat
+
+The default formatter of this library is `StringFormatMessageFormatter`, which uses `string.Format`: a resource value with arguments is a composite format string, and its wording cannot depend on the arguments. The opt-in package `ResXLocalization.MessageFormat` replaces it with [ICU MessageFormat](https://unicode-org.github.io/icu/userguide/format_parse/messages/), whose `plural` and `select` choose the wording by the arguments:
+
+```text
+{Count, plural, one {# file deleted} other {# files deleted}}
+{Gender, select, female {She} male {He} other {They}} replied.
+```
+
+The package formats with the [MessageFormat](https://github.com/jeffijoe/messageformat.net) library by Jeff Hansen (NuGet package `MessageFormat`,
+namespace `Jeffijoe.MessageFormat`).
+
+## Opting in
+
+Add the package next to your UI package:
+
+```shell
+dotnet add package ResXLocalization.MessageFormat
+```
+
+Then install the ICU formatter once, at startup:
+
+```csharp
+using RentADeveloper.ResXLocalization.MessageFormat;
+
+Localizer.Current.UseMessageFormat();
+```
+
+`UseMessageFormat()` assigns the package's ICU formatter to `Localizer.Current.MessageFormatter`, so it applies to every lookup in code
+and in XAML, and makes bound text re-resolve like a language switch.
+
+- **Avalonia:** call it in `BuildAvaloniaApp`, next to the registration of your resource files, so the
+ Avalonia previewer formats with ICU too.
+- **WPF:** call it in `App.OnStartup` for the running application. The WPF designer runs no startup code;
+ to format with ICU there too, call it in a `[ModuleInitializer]` of the application assembly, as
+ [Registering resource files](registration.md#wpf) shows for the registration.
+
+Wherever `UseMessageFormat()` did not run, the default formatter is in place: a lookup without
+arguments shows the resource value as written, for example `{Count, plural, one {# file deleted} other
+{# files deleted}}`, and a lookup with arguments whose value `string.Format` cannot read returns the
+failure text and raises `Localizer.Current.LookupFailed`.
+
+## Every resolved value is ICU
+
+After `UseMessageFormat()`, **every** resolved resource value is parsed as an ICU message, with or without
+arguments: `Localizer.Current.Get(key)`, `Localizer.Current.Get(key, arguments: null)`,
+`Localizer.Current.Get(key, MessageArguments.Empty)`, the indexer `Localizer.Current["Key"]` and
+`{l:Localize Key}` alike. So, also without arguments:
+
+- `It''s ready` renders `It's ready`;
+- `'{literal}'` renders `{literal}`;
+- `Hello {Name}`, looked up without arguments, returns the failure text and raises
+ `Localizer.Current.LookupFailed`, because the variable `Name` is missing.
+
+When you opt in, review every resource value for ICU syntax, including the texts without arguments - see
+[Migrating resource values](#migrating-resource-values). A plain text needs no dummy argument and no
+wrapper. The default formatter (`StringFormatMessageFormatter`) keeps returning a value without arguments
+unchanged.
+
+## `plural` and `select`
+
+| Key | `AppStrings.resx` (English) | `AppStrings.de.resx` (German) |
+| --- | --- | --- |
+| `FilesDeleted` | `{Count, plural, one {# file deleted} other {# files deleted}}` | `{Count, plural, one {# Datei gelöscht} other {# Dateien gelöscht}}` |
+
+In code, build named arguments with `MessageArguments` and pass them to any `Localizer.Current.Get`
+overload:
+
+```csharp
+Localizer.Current.Get(AppStringsKeys.FilesDeleted, MessageArguments.FromTuples(("Count", 1))); // "1 file deleted"
+Localizer.Current.Get(AppStringsKeys.FilesDeleted, MessageArguments.FromObject(new { Count = 5 })); // "5 files deleted"
+```
+
+In XAML, name the `` children of `{l:Localize}`:
+
+```xml
+
+
+
+
+
+
+
+```
+
+Which plural categories exist - `zero`, `one`, `two`, `few`, `many`, `other` - depends on the language.
+`=0` matches an exact value:
+`{Count, plural, =0 {No files deleted} one {# file deleted} other {# files deleted}}` renders
+`No files deleted` for 0. `selectordinal` chooses by ordinal rules:
+`{0, selectordinal, one {#st} two {#nd} few {#rd} other {#th}} place` renders `2nd place` for 2.
+
+`select` chooses by a value's text. A partition display that shows the volume label when there is one:
+
+```text
+{HasLabel, select, True {{Label} ({Letter}:)} other {Local Disk ({Letter}:)}}
+```
+
+```xml
+
+
+
+
+
+```
+
+It renders `Data (D:)` for a partition labeled `Data` on drive `D`, and `Local Disk (C:)` for an
+unlabeled one on drive `C`. A `bool` matches the `select` keys `True` and `False` - .NET's text for a
+`bool` - not `true` and `false`.
+
+An enum label needs only one enum member and a `plural` pattern: give `{l:LocalizeEnum}` the same
+`` children, see [Localizing enum values](enums.md#with-format-arguments).
+
+## Arguments
+
+Every argument reaches ICU under its position - `"0"`, `"1"`, and so on - and, if it has a name, under its
+name as well. A name overwrites a position with the same text:
+
+| Arguments | ICU receives |
+| --- | --- |
+| `` with `Count` = 5 | `{ "0": 5 }`, so `{0, plural, ...}` works |
+| `` and `` | `{ "0": "Data", "1": "D", "Letter": "D" }`, so the pattern may use `{0} ({Letter}:)` or `{0} ({1}:)` |
+| `` and `` | `{ "0": B, "1": B }`: the name wins, silently |
+
+In code, `MessageArguments.FromTuples(("Count", 5))`, `MessageArguments.FromDictionary(dictionary)` and
+`MessageArguments.FromObject(new { Count = 5 })` build named arguments, and
+`MessageArguments.FromValues(5)` positional ones. Named arguments are reachable as `{0}`, `{1}` too, in the
+order the method produced them; in a pattern used with named arguments, write the names.
+
+**A missing variable always fails.** A pattern that references a variable the lookup does not supply
+returns the failure text and raises `Localizer.Current.LookupFailed` with the reason
+`LookupFailureReason.MessageFormatFailed`. The MessageFormat library has no setting that renders a
+missing variable empty.
+
+### `null`, strings and other values
+
+A `null` value never fails:
+
+| Pattern | Renders for `null` |
+| --- | --- |
+| `{0, plural, one {# file} other {# files}}` | `0 files` |
+| `{0, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}` | `0th` |
+| `{0, select, a {A} other {O}}` | `O` - the `other` branch |
+| `{0}`, `{0, number}`, `{0, date}`, `{0, time}` | an empty string |
+
+An argument binding that is not resolved yet passes `null`, so a view that loads before its `DataContext`
+briefly shows `0 people invited` for `{Count, plural, one {# person invited} other {# people invited}}`,
+without `LookupFailed`; a view-model value that is `null` renders the same. The default formatter renders
+every `null` argument as an empty string.
+
+- **A numeric string** behaves like the number in `plural`: `"5"` renders `5 files` and `"1"` renders
+ `1 file`, so the constant `Value="5"` in XAML works.
+- **A non-numeric string** in `plural`, such as `"abc"`, fails with a `FormatException`: failure text
+ and `LookupFailed`. `{0, number}` renders a string unchanged (`abc`), and `select` and `{0}` take any
+ string.
+- **A value that is neither a number nor a string**, such as a plain `object`, fails in `plural` with an
+ `InvalidCastException`: failure text and `LookupFailed`.
+
+## The format culture
+
+ICU formats in the lookup's culture - `Localizer.Current.CurrentCulture` when the lookup runs - with one
+exception: the invariant culture formats as `en`. The MessageFormat library chooses plural rules by the
+culture's name, and for the invariant culture, whose name is empty, it uses CLDR's root rules, which know
+only `other`: `{0, plural, one {# item} other {# items}}` would render `1 items`. The neutral resources
+of most applications are English, so `en` is the better guess. Where `en` cannot be created, as in
+[globalization-invariant mode](#globalization-invariant-mode), the invariant culture stays, with the root
+rules.
+
+Plural rules for every other culture come from CLDR rules generated into the MessageFormat library, which
+follow the culture name's chain down to the root rules by themselves (`de-CH`, then `de`). A culture whose
+name CLDR does not know at all gets the root rules: `other` only. Numbers and dates use .NET's data for
+the culture:
+
+| Culture | Plural category of `1` | `{0, number}` with `1234.5` |
+| --- | --- | --- |
+| `CultureInfo.InvariantCulture` (formats as `en`) | `one` | `1,234.5` |
+| `en` | `one` | `1,234.5` |
+| `de-DE` | `one` | `1.234,5` |
+| `iu-Latn-CA` | `one` | the culture's own format |
+| `zh-Hant-TW` | `other` - Chinese has no `one` | the culture's own format |
+
+### Keep the thread culture in sync
+
+A few places of the MessageFormat library do not use the lookup's culture but the thread's
+`CultureInfo.CurrentCulture`, which `Localizer.Current.CurrentCulture` deliberately does not change:
+
+- `#` in a `plural` branch renders the number in the thread culture (see
+ [`#` uses the thread culture, without grouping](#-uses-the-thread-culture-without-grouping));
+- `select` compares a number or date argument with its keys as the thread culture writes it, so with the
+ thread culture `de-DE` the value 1.5 does not match the key `1.5`;
+- decimal exact-value keys and offsets, such as `=1.5` and `offset:1.5`, are read in the thread culture,
+ so with the thread culture `de-DE` the key `=1.5` does not match the value 1.5. Whole-number keys and
+ offsets, such as `=0`, `=1` and `offset:1`, do not depend on any culture.
+
+It is therefore recommended to keep `CultureInfo.CurrentCulture` in sync with
+`Localizer.Current.CurrentCulture` yourself, for example in a `Localizer.Current.CultureChanged` handler
+that you subscribe before the first assignment of `Localizer.Current.CurrentCulture`:
+
+```csharp
+Localizer.Current.CultureChanged += (_, e) =>
+{
+ CultureInfo.CurrentCulture = e.NewCulture; // the thread that switches the language, normally the UI thread
+ CultureInfo.DefaultThreadCurrentCulture = e.NewCulture; // threads without a culture of their own
+};
+
+Localizer.Current.CurrentCulture = new CultureInfo("de-DE");
+```
+
+The thread culture also decides how the rest of your code formats numbers and dates, for example
+`ToString()` and `string.Format` without a format provider, so this changes those to the selected
+language too - in a localized application usually what you want.
+
+## Styles
+
+Numbers, dates and times are formatted with .NET's culture data, not with CLDR's, and only these styles
+exist (examples in `en-US`):
+
+| Pattern | Renders |
+| --- | --- |
+| `{0, number}` | the culture's number format, grouped: `1,234.5`; `1,234,567` for an integer |
+| `{0, number, integer}` | rounded and **not** grouped: `1234568` for `1234567.6` |
+| `{0, number, currency}` | .NET's `C` format with the culture's own currency: `$3.50`; `3,50 €` in `de-DE` |
+| `{0, number, percent}` | .NET's `P0` format: `26%` for `0.256` |
+| `{0, date}` and `{0, date, short}` | .NET's `d` format: `1/31/2026` |
+| `{0, date, full}` | `Saturday, January 31, 2026` |
+| `{0, time, short}` | `2:05 PM` |
+| `{0, time}` and `{0, time, medium}` | `2:05:09 PM` |
+
+A neutral culture such as `en` or `de` has no currency, so `{0, number, currency}` renders the generic
+currency sign there: `¤3.50`. Use a specific culture such as `en-US` or `de-DE` where amounts of money
+are shown.
+
+Every other style returns the failure text and raises `LookupFailed` with an
+`UnsupportedFormatStyleException`: `{0, date, medium}`, `{0, date, long}`, and number skeletons such as
+`{0, number, ::currency/EUR}`. Add the styles you need with `CustomValueFormatter`, see
+[Configuring the formatter of the MessageFormat library](#configuring-the-formatter-of-the-messageformat-library).
+
+### `#` uses the thread culture, without grouping
+
+In a `plural` branch, `#` renders the number with `CultureInfo.CurrentCulture` - the thread's culture,
+which `Localizer.Current.CurrentCulture` deliberately does not change - and without grouping. With the
+thread culture `en-US` and the lookup culture `de-DE`,
+`{Count, plural, one {# Datei} other {# Dateien}}` renders `1234567 Dateien` for 1234567 and `1.5 Dateien`
+for 1.5. Integer counts below 1,000 are therefore right in every culture, and fractional counts are right
+when you [keep the thread culture in sync](#keep-the-thread-culture-in-sync).
+
+For larger or fractional numbers, write `{Count, number}` in the branch instead of `#`; it uses the
+lookup culture: `{Count, plural, one {{Count, number} Datei} other {{Count, number} Dateien}}` renders
+`1.234.567 Dateien`. Nothing reports a `#` that renders differently from the lookup culture.
+
+## Configuring the formatter of the MessageFormat library
+
+`UseMessageFormat` takes an optional `Jeffijoe.MessageFormat.MessageFormatter`, the extension point of the
+MessageFormat library: custom formatters (`Formatters`), custom plural rules (`CardinalPluralizers`,
+`OrdinalPluralizers`), and `CustomValueFormatter` for further `number`, `date` and `time` styles. This one
+adds `date, medium`:
+
+```csharp
+using System.Globalization;
+using RentADeveloper.ResXLocalization;
+using RentADeveloper.ResXLocalization.MessageFormat;
+using JeffijoeMessageFormatter = Jeffijoe.MessageFormat.MessageFormatter;
+
+var messageFormatter = new JeffijoeMessageFormatter(
+ customValueFormatter: new Jeffijoe.MessageFormat.CustomValueFormatters
+ {
+ // Handles "date, medium"; returning false keeps the built-in behavior for every other style.
+ Date = (CultureInfo culture, object? value, string? style, out string? formatted) =>
+ {
+ if (style == "medium" && value is DateTime date)
+ {
+ formatted = date.ToString("d MMM yyyy", culture);
+ return true;
+ }
+
+ formatted = null;
+ return false;
+ },
+ }
+);
+
+Localizer.Current.UseMessageFormat(messageFormatter);
+
+// {0, date, medium} with new DateTime(2026, 1, 31) now renders "31 Jan 2026" in en.
+```
+
+- **It is used as given.** `UseMessageFormat` does not copy, wrap or reconfigure it. `null`, the default,
+ means a new `MessageFormatter` with the library's defaults.
+- **It is shared by every culture and every thread.** Formatting with it is thread-safe, but its
+ configuration is not: `Formatters` is a list, the plural rules are plain dictionaries, and
+ `CustomValueFormatter` has a setter. Configure it completely before calling `UseMessageFormat`, and do
+ not modify it afterwards.
+- **Its `Culture` property has no effect**, because every lookup passes its own culture.
+- **Its parse cache** keeps one parsed pattern per distinct pattern text and is never trimmed. Resource
+ values bound it; if you format generated patterns, pass `new JeffijoeMessageFormatter(useCache: false)`.
+- **An exception your extensions throw** while formatting is a formatting failure like any other: the
+ lookup returns the failure text and raises `LookupFailed`. Whether your extensions are trim and Native
+ AOT safe is yours to check.
+- **Use an alias.** Both `Jeffijoe.MessageFormat` and `RentADeveloper.ResXLocalization` declare an
+ `IMessageFormatter`, so importing both namespaces in one file makes `IMessageFormatter` ambiguous. Import
+ `Jeffijoe.MessageFormat.MessageFormatter` under an alias, as above.
+
+## Globalization-invariant mode
+
+`UseMessageFormat()` works in globalization-invariant mode and does not throw there. But an application
+built with `InvariantGlobalization=true` - a common setting for Native AOT and for containers - or run
+with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1` cannot create named cultures at all:
+`new CultureInfo("de")` throws a `CultureNotFoundException`. Only the invariant culture is left, and it
+formats with the root plural rules, `other` only.
+
+With `PredefinedCulturesOnly=false` as well, named cultures can be created and their plural rules follow
+their names (`de-CH` chooses `one` for 1), but numbers, dates and currencies format invariantly: `1,234.5`
+in `de-DE`, and `3.50` for a currency. Neither setup is recommended for a localized application.
+
+## Migrating resource values
+
+Only a resource value that contains a brace (`{` or `}`), a doubled apostrophe (`''`) or an apostrophe
+before a number sign (`'#`) can render differently under ICU, or fail. Every other value renders as
+written, including texts with single apostrophes such as `It's ready` or `l'utilisateur`, and texts with
+angle brackets. To find the values to review, search your `.resx` files for the regular expression
+`[{}]|''|'#` - with the find-in-files search of your IDE, or with PowerShell:
+
+```powershell
+Get-ChildItem -Recurse -Filter *.resx | Select-String -Pattern "[{}]|''|'#"
+```
+
+Every value with arguments contains braces, so those values are among the matches too; the tables below
+show what to look for.
+
+ICU syntax is not compatible with composite format strings. These spellings fail under ICU - they return
+the failure text and raise `LookupFailed`, so at least they are reported:
+
+| Composite format | ICU |
+| --- | --- |
+| `{0:N0}` | `{0, number}` (grouped); `{0, number, integer}` rounds without grouping |
+| `{1:d}` | `{1, date, short}` |
+| `{0:C}` | `{0, number, currency}` |
+| `{{literal}}` | `'{'literal'}'` |
+
+ICU parses a resource value whenever it formats one, so a literal brace is syntax even in a text without
+arguments: `Use { and } for blocks` fails, because `and` is read as a missing variable. Write
+`Use '{' and '}' for blocks`.
+
+These values change **silently** - nothing reports them, not even `LookupFailed`:
+
+| Resource value | ICU renders, for the argument value "3" | The default formatter renders |
+| --- | --- | --- |
+| `'{0}' was not found` | `{0} was not found` | `'3' was not found` |
+| `Datei '{0}' wurde gelöscht` | `Datei {0} wurde gelöscht` | `Datei '3' wurde gelöscht` |
+| `Can't find '{Name}'` | `Can't find {Name}` | - |
+| `'{0}'s file` | `{0}s file` | `'3's file` |
+| `''{0}''` | `'3'` | `''3''` |
+| `It''s {0}` | `It's 3` | `It''s 3` |
+| `'#' in text {0}` | `# in text 3` | `'#' in text 3` |
+
+- **`'{0}'` renders the literal text `{0}`**: an apostrophe before a brace starts quoted text. To put an
+ argument in apostrophes, write `''{0}''`, which renders `'3'`.
+- **`''` becomes one `'`.**
+- **Apostrophes in ordinary text need no change**: elisions (`l'utilisateur {0}`), contractions
+ (`Don't delete {0}`) and possessives (`It's {0}'s turn`) render as written, inside a `plural` branch
+ too.
+
+Angle brackets are plain text: `{0} saved` renders `3 saved`, and `Press to {0}`
+renders `Press to 3`. Some other ICU engines read tags as markup; this one does not.
+
+## Using another ICU engine
+
+The formatter is replaceable: `IMessageFormatter` and `ILocalizer.MessageFormatter` are public. If you
+need what this engine does not offer - CLDR-exact number and date formats, number skeletons, `medium` and
+`long` dates, durations, rich-text tags - implement `IMessageFormatter` over another engine and assign it
+to `Localizer.Current.MessageFormatter` **instead of** calling `UseMessageFormat()`.
+
+This adapter formats with [Rh.MessageFormat](https://github.com/Rheopyrin/Rh.Messageformat) (NuGet
+package `Rh.MessageFormat`) and keeps the three rules of this package:
+
+```csharp
+using System.Globalization;
+using RentADeveloper.ResXLocalization;
+using Rh.MessageFormat.Caches;
+using Rh.MessageFormat.Options;
+
+public sealed class RhMessageFormatter : IMessageFormatter
+{
+ // One Rh.MessageFormat formatter per locale, created on first use. A locale Rh.MessageFormat has no
+ // data for falls back to en instead of throwing an InvalidLocaleException.
+ private readonly MessageFormatterCachedProvider formatters = new(
+ new MessageFormatterOptions { DefaultFallbackLocale = "en" }
+ );
+
+ public string Format(string pattern, MessageArguments arguments, CultureInfo culture)
+ {
+ // 1. Every argument under its position, then every named argument under its name.
+ var values = new Dictionary(StringComparer.Ordinal);
+
+ foreach (var argument in arguments)
+ {
+ values[argument.Position.ToString(CultureInfo.InvariantCulture)] = argument.Value;
+ }
+
+ foreach (var argument in arguments)
+ {
+ if (argument.Name is { } name)
+ {
+ values[name] = argument.Value;
+ }
+ }
+
+ // 2. Always parse, also without arguments: then the dictionary is empty.
+ // 3. The dictionary overload of FormatMessage, never FormatMessage(string, object), which reads the
+ // object's properties by reflection and is not trim or Native AOT safe.
+ // The invariant culture has no name, so it formats as en, as UseMessageFormat() does.
+ var locale = culture.Name.Length == 0 ? "en" : culture.Name;
+ return this.formatters.GetFormatter(locale).FormatMessage(pattern, values);
+ }
+}
+```
+
+```csharp
+Localizer.Current.MessageFormatter = new RhMessageFormatter(); // instead of UseMessageFormat()
+```
+
+Do not import the namespace `Rh.MessageFormat.Abstractions.Interfaces` in the adapter's file: it declares
+an `IMessageFormatter` of its own, which makes `IMessageFormatter` ambiguous.
+
+Two warnings:
+
+- **Engines do not accept the same dialect.** Tags, missing variables and styles differ between ICU
+ engines, so resource values written for one engine can render differently, or fail, under another. For
+ example, under Rh.MessageFormat `Hello {Name}` looked up without arguments renders `Hello ` instead of
+ the failure text, and `{0, date, medium}` renders `Jan 31, 2026` instead of the failure text.
+- **Such an adapter is your code.** ResXLocalization does not ship or support it, and its size and its
+ Native AOT safety are yours to check. Rh.MessageFormat carries CLDR data for more than 200 locales:
+ measured with Rh.MessageFormat 1.2.0, it adds about 15 MB to a Native AOT binary.
diff --git a/docs/index.md b/docs/index.md
index a30696b..25563bc 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -15,6 +15,7 @@ installation and a quick start. These pages are the full documentation.
| [Registering resource files](guides/registration.md) | What to register for search-all lookups, where - including the WPF designer and class libraries - dependency injection, resources from other assemblies |
| [Localizing enum values](guides/enums.md) | The naming convention, item templates, the converter, custom prefixes and scoping |
| [Dynamic format arguments](guides/format-arguments.md) | `Get(key, MessageArguments.FromValues(…))`, the `MessageArguments` factory, and `` children of `{l:Localize}` with constant or bound values, optionally named |
+| [ICU MessageFormat](guides/message-format.md) | The opt-in `ResXLocalization.MessageFormat` package: `plural` and `select` through `Localizer.Current.UseMessageFormat()`, argument mapping, format culture, styles, and migrating resource values to ICU syntax |
| [Native AOT and trimming](guides/native-aot.md) | What to declare, how to publish, and why the repository's own gate runs the native binary |
| [Migrating to 2.0](guides/migration-2.0.md) | Each breaking change of 2.0, with what to do |
@@ -33,6 +34,7 @@ The generated reference covers the runtime assemblies:
| [`RentADeveloper.ResXLocalization`](xref:RentADeveloper.ResXLocalization) | `ResXLocalization.Core` | `ILocalizer`, `Localizer`, `ResourceKey` — the shared engine |
| [`RentADeveloper.ResXLocalization.Avalonia`](xref:RentADeveloper.ResXLocalization.Avalonia) | `ResXLocalization.Avalonia` | The Avalonia markup extensions and converter |
| [`RentADeveloper.ResXLocalization.WPF`](xref:RentADeveloper.ResXLocalization.WPF) | `ResXLocalization.WPF` | The WPF markup extensions and converter |
+| [`RentADeveloper.ResXLocalization.MessageFormat`](xref:RentADeveloper.ResXLocalization.MessageFormat) | `ResXLocalization.MessageFormat` | `UseMessageFormat`, which installs the ICU MessageFormat formatter |
## The packages
@@ -41,10 +43,12 @@ The generated reference covers the runtime assemblies:
| `ResXLocalization.Avalonia` | Avalonia 12 | `net8.0`, `net10.0` | Supported |
| `ResXLocalization.WPF` | WPF | `net8.0-windows`, `net10.0-windows` | Not supported — a WPF limitation |
| `ResXLocalization.Core` | none | `net8.0`, `net10.0` | Supported |
+| `ResXLocalization.MessageFormat` | none | `net8.0`, `net10.0` | Supported |
Install the package for your UI framework; it brings the engine, the source generator and the build
wiring with it. Core arrives as a dependency, and one copy of it satisfies both UI packages in an
-application that uses them together.
+application that uses them together. `ResXLocalization.MessageFormat` is optional: add it next to the UI
+package to format with ICU MessageFormat, see [ICU MessageFormat](guides/message-format.md).
## Project
diff --git a/docs/toc.yml b/docs/toc.yml
index d127ddf..d9405fa 100644
--- a/docs/toc.yml
+++ b/docs/toc.yml
@@ -10,6 +10,8 @@
href: guides/enums.md
- name: Dynamic format arguments
href: guides/format-arguments.md
+ - name: ICU MessageFormat
+ href: guides/message-format.md
- name: Native AOT and trimming
href: guides/native-aot.md
- name: Migrating to 2.0
diff --git a/scripts/update-public-api.ps1 b/scripts/update-public-api.ps1
index e4457ec..fa3c11d 100644
--- a/scripts/update-public-api.ps1
+++ b/scripts/update-public-api.ps1
@@ -13,7 +13,7 @@
PublicAPI.Unshipped.txt. It creates the two files first where they are missing: dotnet format applies
the fix but will not create the files, and without them the analyzer reports nothing at all.
- Only the three runtime projects are covered. ResXLocalization.SourceGenerators ships inside the UI
+ Only the four runtime projects are covered. ResXLocalization.SourceGenerators ships inside the UI
packages as an analyzer, has no package identity of its own and no tracked public API; its equivalent
is analyzer release tracking in AnalyzerReleases.*.md, which is a separate file and a separate step.
@@ -27,7 +27,7 @@
maintainer step - see -MarkShipped - and is never part of an ordinary contribution.
.PARAMETER Project
- One or more project files to update. Defaults to the three runtime projects under src/.
+ One or more project files to update. Defaults to the four runtime projects under src/.
.PARAMETER MarkShipped
The MAINTAINER's release step, not the edit step: fold PublicAPI.Unshipped.txt into
@@ -60,7 +60,7 @@ $repositoryRoot = (Resolve-Path -LiteralPath (Split-Path -Parent $PSScriptRoot))
# The runtime projects, named rather than globbed: a glob over src/ would also pick up the source
# generator, which has no public API to track.
-$runtimeProjectNames = @('ResXLocalization.Core', 'ResXLocalization.Avalonia', 'ResXLocalization.WPF')
+$runtimeProjectNames = @('ResXLocalization.Core', 'ResXLocalization.Avalonia', 'ResXLocalization.WPF', 'ResXLocalization.MessageFormat')
if (-not $Project -or $Project.Count -eq 0)
{
diff --git a/src/Directory.Build.props b/src/Directory.Build.props
index e796194..d40b776 100644
--- a/src/Directory.Build.props
+++ b/src/Directory.Build.props
@@ -100,6 +100,11 @@ hold in that pass too.
The baseline is the version currently on nuget.org. At a release it moves to the version being
replaced, alongside the bump in the repository-root Directory.Build.props. -->
true
+
+
+
+
1.1.0
diff --git a/src/ResXLocalization.Core/ILocalizer.cs b/src/ResXLocalization.Core/ILocalizer.cs
index 43ad084..6443c04 100644
--- a/src/ResXLocalization.Core/ILocalizer.cs
+++ b/src/ResXLocalization.Core/ILocalizer.cs
@@ -179,6 +179,11 @@ public interface ILocalizer : INotifyPropertyChanged
/// the one hook for all translated texts (see ).
///
///
+ /// Localizer.Current.UseMessageFormat() from the ResXLocalization.MessageFormat package installs an
+ /// ICU MessageFormat formatter here (plural, select). That formatter parses every resolved
+ /// value as an ICU message, including the values of lookups without arguments.
+ ///
+ ///
/// Assigning a different instance advances ; assigning the
/// current instance again does nothing. Exceptions thrown by
/// handlers propagate from the assignment.
diff --git a/src/ResXLocalization.Core/MessageArgument.cs b/src/ResXLocalization.Core/MessageArgument.cs
index c06a80f..dae9121 100644
--- a/src/ResXLocalization.Core/MessageArgument.cs
+++ b/src/ResXLocalization.Core/MessageArgument.cs
@@ -19,7 +19,10 @@ namespace RentADeveloper.ResXLocalization;
/// for a positional-only argument; otherwise the name under which a formatter
/// that understands names (ICU MessageFormat) also finds the argument. The default
/// () formatter uses positions only and
-/// ignores names.
+/// ignores names. The ICU MessageFormat formatter of the ResXLocalization.MessageFormat package makes every
+/// argument reachable under its position ("0", "1", and so on) and, if it has a name, under
+/// that name as well; a name overwrites a position with the same text, so the argument named "0"
+/// replaces the argument at position 0 as {0}.
///
/// The argument's value; may be .
public readonly record struct MessageArgument(int Position, string? Name, object? Value);
diff --git a/src/ResXLocalization.MessageFormat/GlobalUsings.cs b/src/ResXLocalization.MessageFormat/GlobalUsings.cs
new file mode 100644
index 0000000..8b812c5
--- /dev/null
+++ b/src/ResXLocalization.MessageFormat/GlobalUsings.cs
@@ -0,0 +1,4 @@
+global using System.Globalization;
+// An alias rather than the namespace: Jeffijoe.MessageFormat declares an IMessageFormatter of its own, which
+// would make RentADeveloper.ResXLocalization.IMessageFormatter ambiguous.
+global using JeffijoeMessageFormatter = Jeffijoe.MessageFormat.MessageFormatter;
diff --git a/src/ResXLocalization.MessageFormat/IcuMessageFormatter.cs b/src/ResXLocalization.MessageFormat/IcuMessageFormatter.cs
new file mode 100644
index 0000000..bfabfa0
--- /dev/null
+++ b/src/ResXLocalization.MessageFormat/IcuMessageFormatter.cs
@@ -0,0 +1,85 @@
+namespace RentADeveloper.ResXLocalization.MessageFormat;
+
+///
+/// The ICU MessageFormat that
+/// installs. It formats every resolved value
+/// with one , also a value without arguments.
+///
+///
+/// The formatter of the MessageFormat library, used as given for every culture and every thread.
+///
+internal sealed class IcuMessageFormatter(JeffijoeMessageFormatter messageFormatter) : IMessageFormatter
+{
+ ///
+ /// The culture to format in when the lookup culture is the invariant culture: en, or the invariant
+ /// culture itself where en cannot be created (globalization-invariant mode).
+ ///
+ private readonly CultureInfo englishCulture = ResolveEnglishCulture();
+
+ /// The formatter of the MessageFormat library.
+ private readonly JeffijoeMessageFormatter messageFormatter = messageFormatter;
+
+ ///
+ /// Formats as an ICU message, also when is empty.
+ /// Every argument is passed under its ("0", "1", and
+ /// so on) and, if it has a , under that name as well; a name overwrites
+ /// a position with the same text.
+ ///
+ /// The resolved resource value.
+ /// The arguments of the lookup; never .
+ ///
+ /// The culture to format in. The invariant culture formats as en, because the plural rules of the
+ /// MessageFormat library for the invariant culture know only the category other.
+ ///
+ /// The formatted message.
+ ///
+ /// is not a valid ICU message, references a variable
+ /// does not supply, or uses an unsupported style. The localizer catches it,
+ /// like any other exception of a formatter, and returns the failure text.
+ ///
+ /// A plural argument is a string that doesn't represent a number.
+ ///
+ /// A plural argument is neither a number nor a string.
+ ///
+ public string Format(string pattern, MessageArguments arguments, CultureInfo culture)
+ {
+ var values = new Dictionary(StringComparer.Ordinal);
+
+ foreach (var argument in arguments)
+ {
+ values[argument.Position.ToString(CultureInfo.InvariantCulture)] = argument.Value;
+ }
+
+ // A second pass, so that a name overwrites a position whatever the order of the arguments.
+ foreach (var argument in arguments)
+ {
+ if (argument.Name is { } name)
+ {
+ values[name] = argument.Value;
+ }
+ }
+
+ return this.messageFormatter.FormatMessage(
+ pattern,
+ values,
+ culture.Name.Length == 0 ? this.englishCulture : culture
+ );
+ }
+
+ ///
+ /// Returns en, or the invariant culture when en cannot be created, as in
+ /// globalization-invariant mode with only predefined cultures allowed.
+ ///
+ /// The culture that replaces the invariant culture when formatting.
+ private static CultureInfo ResolveEnglishCulture()
+ {
+ try
+ {
+ return CultureInfo.GetCultureInfo("en");
+ }
+ catch (CultureNotFoundException)
+ {
+ return CultureInfo.InvariantCulture;
+ }
+ }
+}
diff --git a/src/ResXLocalization.MessageFormat/MessageFormatLocalizerExtensions.cs b/src/ResXLocalization.MessageFormat/MessageFormatLocalizerExtensions.cs
new file mode 100644
index 0000000..6b9cb84
--- /dev/null
+++ b/src/ResXLocalization.MessageFormat/MessageFormatLocalizerExtensions.cs
@@ -0,0 +1,57 @@
+namespace RentADeveloper.ResXLocalization.MessageFormat;
+
+///
+/// Installs ICU MessageFormat as the formatter of an , for messages whose shape
+/// depends on their arguments, such as {Count, plural, one {# file deleted} other {# files deleted}}.
+///
+public static class MessageFormatLocalizerExtensions
+{
+ ///
+ /// Replaces the of with the ICU
+ /// MessageFormat formatter, for every lookup in code and in XAML. Call it once, at startup:
+ /// Localizer.Current.UseMessageFormat();
+ ///
+ ///
+ ///
+ /// After the call, every resolved resource value is parsed as an ICU message, also for a lookup without
+ /// arguments: Localizer.Current.Get("Key"), the indexer, and
+ /// {l:Localize Key} of the ResXLocalization.Avalonia and ResXLocalization.WPF packages. Every
+ /// resource value must therefore follow ICU syntax, including texts without arguments: It''s ready
+ /// renders It's ready, '{literal}' renders {literal}, and a value that references a
+ /// variable the lookup does not supply returns the failure text and raises
+ /// .
+ ///
+ ///
+ /// Named arguments are built with , for example
+ /// Localizer.Current.Get(AppStringsKeys.FilesDeleted, MessageArguments.FromTuples(("Count", 5))), and
+ /// declared in XAML as <l:Argument Name="Count" Value="{Binding DeletedCount}" />. Every
+ /// argument is also reachable under its position: {0}, {1} and so on.
+ ///
+ ///
+ /// The method works with any implementation, because it only assigns
+ /// . An exception thrown by the setter of a custom implementation,
+ /// or by a handler during the
+ /// assignment, propagates.
+ ///
+ ///
+ /// See ICU MessageFormat.
+ ///
+ ///
+ ///
+ /// The localizer whose formatter to replace, usually .
+ ///
+ ///
+ /// The of the MessageFormat library that formats every
+ /// message, or (the default) for a new one with the library's defaults. A non-null
+ /// instance is used as given, with its custom formatters, pluralizers and CustomValueFormatter, and
+ /// is shared by every culture and every thread: configure it completely before the call, and do not modify
+ /// it afterwards. Its Culture property has no effect, because every lookup passes its own culture.
+ ///
+ /// is .
+ public static void UseMessageFormat(this ILocalizer localizer, JeffijoeMessageFormatter? messageFormatter = null)
+ {
+ ArgumentNullException.ThrowIfNull(localizer);
+
+ localizer.MessageFormatter = new IcuMessageFormatter(messageFormatter ?? new JeffijoeMessageFormatter());
+ }
+}
diff --git a/src/ResXLocalization.MessageFormat/PublicAPI.Shipped.txt b/src/ResXLocalization.MessageFormat/PublicAPI.Shipped.txt
new file mode 100644
index 0000000..7dc5c58
--- /dev/null
+++ b/src/ResXLocalization.MessageFormat/PublicAPI.Shipped.txt
@@ -0,0 +1 @@
+#nullable enable
diff --git a/src/ResXLocalization.MessageFormat/PublicAPI.Unshipped.txt b/src/ResXLocalization.MessageFormat/PublicAPI.Unshipped.txt
new file mode 100644
index 0000000..0d945e0
--- /dev/null
+++ b/src/ResXLocalization.MessageFormat/PublicAPI.Unshipped.txt
@@ -0,0 +1,3 @@
+#nullable enable
+RentADeveloper.ResXLocalization.MessageFormat.MessageFormatLocalizerExtensions
+static RentADeveloper.ResXLocalization.MessageFormat.MessageFormatLocalizerExtensions.UseMessageFormat(this RentADeveloper.ResXLocalization.ILocalizer! localizer, Jeffijoe.MessageFormat.MessageFormatter? messageFormatter = null) -> void
diff --git a/src/ResXLocalization.MessageFormat/ResXLocalization.MessageFormat.csproj b/src/ResXLocalization.MessageFormat/ResXLocalization.MessageFormat.csproj
new file mode 100644
index 0000000..e4d3288
--- /dev/null
+++ b/src/ResXLocalization.MessageFormat/ResXLocalization.MessageFormat.csproj
@@ -0,0 +1,22 @@
+
+
+
+ true
+
+ $(LibraryTargetFrameworks)
+
+
+
+ The opt-in ICU MessageFormat formatter for ResXLocalization: plural and select messages for every localized text, in code and in XAML. Activated with Localizer.Current.UseMessageFormat().
+ localization;resx;i18n;l10n;icu;messageformat;plural;aot
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/ResXLocalization.MessageFormat.Tests/DictionaryResourceManager.cs b/tests/ResXLocalization.MessageFormat.Tests/DictionaryResourceManager.cs
new file mode 100644
index 0000000..515f2a6
--- /dev/null
+++ b/tests/ResXLocalization.MessageFormat.Tests/DictionaryResourceManager.cs
@@ -0,0 +1,19 @@
+namespace RentADeveloper.ResXLocalization.MessageFormat.Tests;
+
+///
+/// A over in-memory values, so that ICU patterns need no .resx file.
+/// Every value is a neutral value: it is returned for every culture.
+///
+/// The resource keys and their values.
+internal sealed class DictionaryResourceManager(params (string Key, string Value)[] values) : ResourceManager
+{
+ /// The values, keyed by resource key.
+ private readonly Dictionary values = values.ToDictionary(
+ entry => entry.Key,
+ entry => entry.Value,
+ StringComparer.Ordinal
+ );
+
+ ///
+ public override string? GetString(string name, CultureInfo? culture) => this.values.GetValueOrDefault(name);
+}
diff --git a/tests/ResXLocalization.MessageFormat.Tests/GlobalUsings.cs b/tests/ResXLocalization.MessageFormat.Tests/GlobalUsings.cs
new file mode 100644
index 0000000..0cd6a01
--- /dev/null
+++ b/tests/ResXLocalization.MessageFormat.Tests/GlobalUsings.cs
@@ -0,0 +1,8 @@
+global using System.Globalization;
+global using System.Resources;
+global using AwesomeAssertions;
+global using RentADeveloper.ResXLocalization.Core.Tests;
+global using Xunit;
+// An alias rather than the namespace: Jeffijoe.MessageFormat declares an IMessageFormatter of its own, which
+// would make RentADeveloper.ResXLocalization.IMessageFormatter ambiguous.
+global using JeffijoeMessageFormatter = Jeffijoe.MessageFormat.MessageFormatter;
diff --git a/tests/ResXLocalization.MessageFormat.Tests/IcuMessageFormatTests.cs b/tests/ResXLocalization.MessageFormat.Tests/IcuMessageFormatTests.cs
new file mode 100644
index 0000000..2781b0f
--- /dev/null
+++ b/tests/ResXLocalization.MessageFormat.Tests/IcuMessageFormatTests.cs
@@ -0,0 +1,454 @@
+using Jeffijoe.MessageFormat.Formatting;
+
+namespace RentADeveloper.ResXLocalization.MessageFormat.Tests;
+
+///
+/// Exercises and the ICU MessageFormat
+/// formatter it installs, through the lookups of a : ICU syntax for every resolved
+/// value, with or without arguments, the mapping of positional and named arguments, the format culture, and
+/// the formatting failures that return the failure text and raise .
+///
+public class IcuMessageFormatTests
+{
+ private const string FailureText = "!Key!";
+ private const string Key = "Key";
+
+ [Theory]
+ [InlineData("{0} saved", "3 saved")]
+ [InlineData("Press to {0}", "Press to 3")]
+ public void AngleBrackets_AreText(string pattern, string expected) =>
+ FormatShouldReturn(CreateLocalizer(), pattern, MessageArguments.FromValues(3), expected);
+
+ [Theory]
+ [InlineData("l'utilisateur {0}", "l'utilisateur 3", "en")]
+ [InlineData("Supprimer l'élément « {0} » ?", "Supprimer l'élément « 3 » ?", "en")]
+ [InlineData("Don't delete {0}", "Don't delete 3", "en")]
+ [InlineData("It's {0}'s turn", "It's 3's turn", "en")]
+ [InlineData("Rock 'n' roll {0}", "Rock 'n' roll 3", "en")]
+ [InlineData("trailing quote {0}'", "trailing quote 3'", "en")]
+ [InlineData("{0, plural, one {Don't delete # file} other {Don't delete # files}}", "Don't delete 3 files", "en")]
+ [InlineData("{0, plural, one {l'élément} other {les # éléments}}", "les 3 éléments", "fr")]
+ [InlineData("'{0}' was not found", "{0} was not found", "en")]
+ [InlineData("Datei '{0}' wurde gelöscht", "Datei {0} wurde gelöscht", "en")]
+ [InlineData("Can't find '{Name}'", "Can't find {Name}", "en")]
+ [InlineData("'{0}'s file", "{0}s file", "en")]
+ [InlineData("''{0}''", "'3'", "en")]
+ [InlineData("It''s {0}", "It's 3", "en")]
+ [InlineData("'{'literal'}' {0}", "{literal} 3", "en")]
+ [InlineData("'#' in text {0}", "# in text 3", "en")]
+ [InlineData("Press to {0}", "Press to 3", "en")]
+ [InlineData("List of {0}", "List of 3", "en")]
+ [InlineData("{0} saved", "3 saved", "en")]
+ [InlineData("a < b is {0}", "a < b is 3", "en")]
+ public void ApostrophesAndAngleBrackets_RenderAsIcuDefinesThem(string pattern, string expected, string cultureName)
+ {
+ var localizer = CreateLocalizer();
+ localizer.CurrentCulture = new CultureInfo(cultureName);
+
+ FormatShouldReturn(localizer, pattern, MessageArguments.FromTuples((null, 3), ("Name", "Bob")), expected);
+ }
+
+ [Fact]
+ public void ArgumentWithoutStyle_IsFormattedWithoutGrouping() =>
+ FormatShouldReturn(CreateLocalizer(), "{0} people", MessageArguments.FromValues(1234567), "1234567 people");
+
+ [Fact]
+ public void CompositeFormatSyntax_ReturnsTheFailureText()
+ {
+ var localizer = CreateLocalizer();
+
+ FormatShouldFail(localizer, "{0:N0} people", MessageArguments.FromValues(1234567))
+ .Exception.Should()
+ .BeAssignableTo();
+ FormatShouldFail(
+ localizer,
+ "{1:d}",
+ MessageArguments.FromValues(1, new DateTime(2026, 1, 31, 0, 0, 0, DateTimeKind.Unspecified))
+ );
+ FormatShouldFail(localizer, "{{literal}}", MessageArguments.FromValues(1));
+ FormatShouldFail(localizer, "a { b } c", MessageArguments.FromValues(1))
+ .Exception.Should()
+ .BeOfType()
+ .Which.MissingVariable.Should()
+ .Be("b");
+ }
+
+ [Fact]
+ public void Formatter_IsSafeForConcurrentUse()
+ {
+ const string pattern = "{Count, plural, one {# file} other {# files}} {Size, number}";
+ var formatter = CreateLocalizer().MessageFormatter;
+ CultureInfo[] cultures = [CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de-DE")];
+
+ // Input 0 to 3: the culture alternates with every input, the count changes every second input.
+ string FormatInput(int input) =>
+ formatter.Format(
+ pattern,
+ MessageArguments.FromTuples(("Count", input < 2 ? 1 : 5), ("Size", 1234.5)),
+ cultures[input % 2]
+ );
+
+ var expected = Enumerable.Range(0, 4).Select(FormatInput).ToArray();
+ expected.Should().Equal("1 file 1,234.5", "1 file 1.234,5", "5 files 1,234.5", "5 files 1.234,5");
+
+ var mismatches = 0;
+ var threads = Enumerable
+ .Range(0, 8)
+ .Select(thread => new Thread(() =>
+ {
+ for (var call = 0; call < 1000; call++)
+ {
+ var input = (thread + call) % 4;
+
+ if (FormatInput(input) != expected[input])
+ {
+ Interlocked.Increment(ref mismatches);
+ }
+ }
+ }))
+ .ToList();
+
+ threads.ForEach(thread => thread.Start());
+ threads.ForEach(thread => thread.Join());
+
+ mismatches.Should().Be(0);
+ }
+
+ [Fact]
+ public void MissingVariable_ReturnsTheFailureText_WithVariableNotFoundException() =>
+ FormatShouldFail(CreateLocalizer(), "{Nope} x", MessageArguments.FromValues(1))
+ .Exception.Should()
+ .BeOfType()
+ .Which.Message.Should()
+ .Contain("Nope");
+
+ [Fact]
+ public void MixedArguments_AreReachableUnderTheirPositionAndTheirName() =>
+ FormatShouldReturn(
+ CreateLocalizer(),
+ "{0} ({Letter}:)",
+ MessageArguments.FromTuples((null, "Data"), ("Letter", "D")),
+ "Data (D:)"
+ );
+
+ [Fact]
+ public void NameThatIsAPosition_OverwritesThatPosition() =>
+ FormatShouldReturn(CreateLocalizer(), "{0}|{1}", MessageArguments.FromTuples((null, "a"), ("0", "b")), "b|b");
+
+ [Fact]
+ public void NamedArguments_WorkThroughEveryGetOverload()
+ {
+ const string pattern = "{Count, plural, one {# file} other {# files}}";
+ var resourceManager = new DictionaryResourceManager(
+ ("Files", pattern),
+ ("Enum_TestKind_A", pattern),
+ ("Prefix_TestKind_A", pattern)
+ );
+ var localizer = CreateLocalizer();
+ localizer.RegisterResourceManager(resourceManager);
+ ILocalizer interfaceLocalizer = localizer;
+ var count = MessageArguments.FromTuples(("Count", 1));
+ using var monitor = localizer.Monitor();
+
+ string[] results =
+ [
+ localizer.Get("Files", MessageArguments.FromTuples(("Count", 1))),
+ interfaceLocalizer.Get(
+ "Files",
+ MessageArguments.FromDictionary(new Dictionary { ["Count"] = 1 })
+ ),
+ localizer.Get("Files", MessageArguments.FromObject(new { Count = 1 }), resourceManager),
+ localizer.Get(new ResourceKey("Files", resourceManager), count),
+ interfaceLocalizer.Get(TestKind.A, count, resourceManager),
+ localizer.Get(TestKind.A, count, resourceManager, "Prefix_"),
+ ];
+
+ results.Should().AllBe("1 file");
+ monitor.Should().NotRaise(nameof(ILocalizer.LookupFailed));
+ }
+
+ [Theory]
+ [InlineData("{0, plural, one {# file} other {# files}}", "0 files")]
+ [InlineData("{0, number}", "")]
+ [InlineData("{0, select, a {A} other {O}}", "O")]
+ [InlineData("{0}", "")]
+ public void NullArgument_RendersWithoutAFailure(string pattern, string expected) =>
+ FormatShouldReturn(CreateLocalizer(), pattern, MessageArguments.FromValues((object?)null), expected);
+
+ [Fact]
+ public void NumberStyle_FollowsTheLookupCulture()
+ {
+ var localizer = CreateLocalizer();
+
+ FormatShouldReturn(localizer, "{0, number}", MessageArguments.FromValues(1234.5), "1,234.5");
+
+ localizer.CurrentCulture = new CultureInfo("de-DE");
+
+ FormatShouldReturn(localizer, "{0, number}", MessageArguments.FromValues(1234.5), "1.234,5");
+ }
+
+ [Fact]
+ public void NumberStyle_GroupsDigits_AndTheIntegerStyleDoesNot()
+ {
+ var localizer = CreateLocalizer();
+
+ FormatShouldReturn(localizer, "{0, number}", MessageArguments.FromValues(1234567), "1,234,567");
+ FormatShouldReturn(localizer, "{0, number, integer}", MessageArguments.FromValues(1234567), "1234567");
+ }
+
+ [Fact]
+ public void Plural_AcceptsNumericStrings_AndFailsForOtherStrings()
+ {
+ const string pattern = "{0, plural, one {# file} other {# files}}";
+ var localizer = CreateLocalizer();
+
+ FormatShouldReturn(localizer, pattern, MessageArguments.FromValues("5"), "5 files");
+ FormatShouldReturn(localizer, pattern, MessageArguments.FromValues("1"), "1 file");
+ FormatShouldFail(localizer, pattern, MessageArguments.FromValues("abc"));
+ }
+
+ [Theory]
+ [InlineData("", "1 item")]
+ [InlineData("en", "1 item")]
+ [InlineData("de-CH", "1 item")]
+ [InlineData("iu-Latn-CA", "1 item")]
+ [InlineData("zh-Hant-TW", "1 items")]
+ public void Plural_FollowsThePluralRulesOfTheLookupCulture(string cultureName, string expected)
+ {
+ var localizer = CreateLocalizer();
+
+ // An empty culture name is the invariant culture, which formats as en.
+ localizer.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
+
+ FormatShouldReturn(
+ localizer,
+ "{0, plural, one {# item} other {# items}}",
+ MessageArguments.FromValues(1),
+ expected
+ );
+ }
+
+ [Fact]
+ public void Plural_SelectsTheBranchOfTheCount()
+ {
+ const string pattern = "{0, plural, one {# person invited} other {# people invited}}";
+ var localizer = CreateLocalizer();
+
+ FormatShouldReturn(localizer, pattern, MessageArguments.FromValues(1), "1 person invited");
+ FormatShouldReturn(localizer, pattern, MessageArguments.FromValues(5), "5 people invited");
+ }
+
+ [Fact]
+ public void ShortDateStyle_FormatsLikeTheEngineInTheLookupCulture()
+ {
+ var date = new DateTime(2026, 1, 31, 0, 0, 0, DateTimeKind.Unspecified);
+ var expected = new JeffijoeMessageFormatter().FormatMessage(
+ "{1, date, short}",
+ new Dictionary { ["0"] = 0, ["1"] = date },
+ CultureInfo.GetCultureInfo("en")
+ );
+
+ expected.Should().NotBe(FailureText);
+ FormatShouldReturn(CreateLocalizer(), "{1, date, short}", MessageArguments.FromValues(0, date), expected);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("iu-Latn-CA")]
+ public void SimpleArgument_FormatsInEveryCulture(string cultureName)
+ {
+ var localizer = CreateLocalizer();
+
+ // An empty culture name is the invariant culture.
+ localizer.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
+
+ FormatShouldReturn(localizer, "{0} items", MessageArguments.FromValues(5), "5 items");
+ }
+
+ [Fact]
+ public void UseMessageFormat_NullLocalizer_ThrowsArgumentNullException()
+ {
+ var act = () => ((ILocalizer)null!).UseMessageFormat();
+
+ act.Should().Throw().WithParameterName("localizer");
+ }
+
+ [Fact]
+ public void UseMessageFormat_TheLookupCultureWinsOverTheCultureOfTheGivenFormatter()
+ {
+ var localizer = new Localizer { CurrentCulture = new CultureInfo("en") };
+ localizer.UseMessageFormat(new JeffijoeMessageFormatter(culture: CultureInfo.GetCultureInfo("de-DE")));
+
+ FormatShouldReturn(localizer, "{0, number}", MessageArguments.FromValues(1234.5), "1,234.5");
+ }
+
+ [Fact]
+ public void UseMessageFormat_UsesTheGivenFormatterAsGiven()
+ {
+ const string pattern = "{0, date, medium}";
+ var arguments = MessageArguments.FromValues(new DateTime(2026, 1, 31, 0, 0, 0, DateTimeKind.Unspecified));
+ var localizer = CreateLocalizer();
+
+ FormatShouldFail(localizer, pattern, arguments).Exception.Should().BeOfType();
+
+ localizer.UseMessageFormat(
+ new JeffijoeMessageFormatter(
+ customValueFormatter: new Jeffijoe.MessageFormat.CustomValueFormatters
+ {
+ Date = (CultureInfo culture, object? value, string? style, out string? formatted) =>
+ {
+ if (style == "medium" && value is DateTime date)
+ {
+ formatted = date.ToString("d MMM yyyy", culture);
+ return true;
+ }
+
+ formatted = string.Empty;
+ return false;
+ },
+ }
+ )
+ );
+
+ FormatShouldReturn(localizer, pattern, arguments, "31 Jan 2026");
+ }
+
+ [Fact]
+ public void UseMessageFormat_WithNullOrWithoutAFormatter_UsesANewFormatter()
+ {
+ var withNull = new Localizer { CurrentCulture = new CultureInfo("en") };
+ withNull.UseMessageFormat(null);
+
+ foreach (var localizer in new[] { withNull, CreateLocalizer() })
+ {
+ FormatShouldReturn(
+ localizer,
+ "{0, plural, one {# file} other {# files}}",
+ MessageArguments.FromValues(1),
+ "1 file"
+ );
+ FormatShouldFail(localizer, "{Nope} x", MessageArguments.FromValues(1));
+ }
+ }
+
+ [Theory]
+ [InlineData("Hello", "Hello")]
+ [InlineData("It''s ready", "It's ready")]
+ [InlineData("'{literal}'", "{literal}")]
+ public void ValueWithoutArguments_IsParsedAsIcu(string pattern, string expected)
+ {
+ var localizer = CreateLocalizer();
+ using var monitor = localizer.Monitor();
+
+ LookUpWithoutArguments(localizer, pattern).Should().AllBe(expected);
+ monitor.Should().NotRaise(nameof(ILocalizer.LookupFailed));
+ }
+
+ [Theory]
+ [InlineData("{Count} a { b } c")]
+ [InlineData("It''s {0}")]
+ public void ValueWithoutArguments_ReferencingAVariable_ReturnsTheFailureText(string pattern)
+ {
+ var localizer = CreateLocalizer();
+ using var monitor = localizer.Monitor();
+
+ LookUpWithoutArguments(localizer, pattern).Should().AllBe(FailureText);
+ monitor
+ .LookupFailures()
+ .Should()
+ .HaveCount(5)
+ .And.AllSatisfy(failure =>
+ {
+ failure.Reason.Should().Be(LookupFailureReason.MessageFormatFailed);
+ failure.Exception.Should().BeOfType();
+ });
+ }
+
+ [Fact]
+ public void WithoutUseMessageFormat_TheDefaultFormatterFormats() =>
+ FormatShouldReturn(
+ new Localizer { CurrentCulture = new CultureInfo("en") },
+ "{0:N0} people",
+ MessageArguments.FromValues(1234567),
+ "1,234,567 people"
+ );
+
+ /// Creates a localizer in the culture en with the ICU formatter installed.
+ /// The localizer.
+ private static Localizer CreateLocalizer()
+ {
+ var localizer = new Localizer { CurrentCulture = new CultureInfo("en") };
+ localizer.UseMessageFormat();
+ return localizer;
+ }
+
+ /// Looks up under with a scoped lookup.
+ /// The localizer.
+ /// The resource value.
+ /// The arguments of the lookup.
+ /// The result of the lookup.
+ private static string Format(Localizer localizer, string pattern, MessageArguments arguments) =>
+ localizer.Get(Key, arguments, new DictionaryResourceManager((Key, pattern)));
+
+ ///
+ /// Asserts that looking up returns the failure text and raises exactly one
+ /// with the reason .
+ ///
+ /// The localizer.
+ /// The resource value.
+ /// The arguments of the lookup.
+ /// The failure the event reported.
+ private static LookupFailure FormatShouldFail(Localizer localizer, string pattern, MessageArguments arguments)
+ {
+ using var monitor = localizer.Monitor();
+
+ Format(localizer, pattern, arguments).Should().Be(FailureText);
+
+ var failure = monitor.LookupFailures().Should().ContainSingle().Which;
+ failure.Reason.Should().Be(LookupFailureReason.MessageFormatFailed);
+ return failure;
+ }
+
+ ///
+ /// Asserts that looking up returns and raises no
+ /// .
+ ///
+ /// The localizer.
+ /// The resource value.
+ /// The arguments of the lookup.
+ /// The expected result.
+ private static void FormatShouldReturn(
+ Localizer localizer,
+ string pattern,
+ MessageArguments arguments,
+ string expected
+ )
+ {
+ using var monitor = localizer.Monitor();
+
+ Format(localizer, pattern, arguments).Should().Be(expected);
+
+ monitor.Should().NotRaise(nameof(ILocalizer.LookupFailed));
+ }
+
+ ///
+ /// Looks up with every form of a lookup without arguments: no arguments,
+ /// , , and empty positional and named arguments.
+ ///
+ /// The localizer.
+ /// The resource value.
+ /// The five results.
+ private static string[] LookUpWithoutArguments(Localizer localizer, string pattern)
+ {
+ var resourceManager = new DictionaryResourceManager((Key, pattern));
+
+ return
+ [
+ localizer.Get(Key, resourceManager: resourceManager),
+ localizer.Get(Key, arguments: null, resourceManager: resourceManager),
+ localizer.Get(Key, MessageArguments.Empty, resourceManager),
+ localizer.Get(Key, MessageArguments.FromValues(), resourceManager),
+ localizer.Get(Key, MessageArguments.FromDictionary(new Dictionary()), resourceManager),
+ ];
+ }
+}
diff --git a/tests/ResXLocalization.MessageFormat.Tests/ResXLocalization.MessageFormat.Tests.csproj b/tests/ResXLocalization.MessageFormat.Tests/ResXLocalization.MessageFormat.Tests.csproj
new file mode 100644
index 0000000..076d053
--- /dev/null
+++ b/tests/ResXLocalization.MessageFormat.Tests/ResXLocalization.MessageFormat.Tests.csproj
@@ -0,0 +1,17 @@
+
+
+
+
+ $(LibraryTargetFrameworks)
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/ResXLocalization.MessageFormat.Tests/TestKind.cs b/tests/ResXLocalization.MessageFormat.Tests/TestKind.cs
new file mode 100644
index 0000000..566f7e2
--- /dev/null
+++ b/tests/ResXLocalization.MessageFormat.Tests/TestKind.cs
@@ -0,0 +1,8 @@
+namespace RentADeveloper.ResXLocalization.MessageFormat.Tests;
+
+/// Test-only enumeration for the enum lookups with named arguments.
+public enum TestKind
+{
+ /// Localized as Enum_TestKind_A and Prefix_TestKind_A.
+ A = 0,
+}