Documentation
¶
Overview ¶
Package i18n reads the languages people read and picks, of those an app is written in, the one that suits them best, and says an app's messages in it.
A language is a BCP 47 tag, as "en", "en-GB", "zh-Hant" or "sr-Latn-RS". Normalize reads the other forms desktops report, as the POSIX locales of Linux ("zh_CN.UTF-8", "sr_RS@latin"). Match compares tags by the distances of the Unicode CLDR, through golang.org/x/text/language, so that zh-TW gets zh-Hant and not zh-Hans, es-MX gets es-419 before es, and nb gets no.
An app's messages are in catalogs (Catalog), a JSON file per language, of messages of ICU MessageFormat (Message), whose plural forms follow the plural rules of CLDR (PluralCategory). `golet generate` writes typed Go and TypeScript functions for them, which say them in the language the app shows (Locale). The data of CLDR is generated from a pinned release (CLDRVersion) by `go generate`.
FormatNumber and FormatDate write numbers, dates and times in the way of a locale, by CLDR's data of the locales of its modern coverage, as ICU and Intl write them; Months, Weekdays and DayPeriods give their names, FirstWeekday and HourCycle a region's week and clock, and Autonym the name of a language in itself. The data is linked into an app only when it formats something.
Index ¶
- Constants
- func Autonym(tag string) string
- func Base(tag string) string
- func DayPeriods(locale string, w Width) (am, pm string)
- func FirstWeekday(locale string) time.Weekday
- func FormatDate(locale string, t time.Time, o DateOptions) string
- func FormatLocales() []string
- func FormatNumber(locale string, n any, o NumberOptions) string
- func HourCycle(locale string) int
- func IsPseudo(tag string) bool
- func Languages() []string
- func Locale() string
- func Match(preferred, supported []string) string
- func Months(locale string, w Width, standAlone bool) [12]string
- func Normalize(locale string) string
- func Parent(tag string) string
- func Register(c *Catalog)
- func SetLocaleFunc(f func() string)
- func Weekdays(locale string, w Width, standAlone bool) [7]string
- type Arg
- type Catalog
- func (c *Catalog) Add(fsys fs.FS) error
- func (c *Catalog) Format(locale, key string, args map[string]any) string
- func (c *Catalog) Languages() []string
- func (c *Catalog) Message(locale, key string) (m *Message, lang string, ok bool)
- func (c *Catalog) Namespace() string
- func (c *Catalog) Source() string
- type DateFormatter
- type DateOptions
- type Dir
- type Message
- type NumberFormatter
- type NumberOptions
- type Operands
- type Plural
- type Region
- type Style
- type SyntaxError
- type Width
Examples ¶
Constants ¶
const ( // PseudoAccents is en-XA: the letters accented, the text a third // longer and in brackets, "[Šéļéçţ ƒîļéš one two]", to find strings // that are not in the catalog, are cut, or are put together from // pieces. PseudoAccents = "en-XA" // PseudoBidi is ar-XB: the source's words shown right to left, as // Arabic or Hebrew text lays out, with the layout of the app right to // left too (Direction is RightToLeft), to find what does not mirror. PseudoBidi = "ar-XB" )
The pseudo locales, which test an app's layouts without translations, as Android's: their messages are the source language's, transformed.
const CLDRVersion = "48.2.0"
CLDRVersion is the release of the Unicode CLDR the data of the package comes from.
Variables ¶
This section is empty.
Functions ¶
func Autonym ¶
Autonym returns the name of a language in itself, for menus of languages: "English", "British English", "Deutsch", "español latinoamericano", "简体中文", "繁體中文", "日本語", in CLDR's form, as Intl.DisplayNames writes it (lowercase in the languages that write names so: "français"). A locale of a region or script has its own name where CLDR has it ("zh-Hant" is "繁體中文"), else the name of the language with them ("português (Brasil)"). It returns "" for a language CLDR has no data of in its modern coverage.
func Base ¶
Base returns the language of tag, without its script and region: "zh" for "zh-Hant-TW", "he" for "iw". It returns "" when tag names no language.
func DayPeriods ¶
DayPeriods returns the names of the halves of the day in locale, before noon and after, in a width: "AM" and "PM" in English, "上午" and "下午" in Chinese.
func FirstWeekday ¶
FirstWeekday returns the day weeks start on in locale, as calendars show them: that of its region by CLDR's week data, or of the region its language is most likely spoken in, Sunday for "en" (the United States) and Monday for "en-GB" and "de", or the one its extension names ("en-US-u-fw-mon").
func FormatDate ¶
func FormatDate(locale string, t time.Time, o DateOptions) string
FormatDate writes t, in its location, in the way of locale, in the Gregorian calendar: the locale's names of months, weekdays and day periods, its patterns, and its digits.
Time zones other than UTC are written as offsets from GMT in the locale's format, "GMT+8", "GMT+05:30", where ICU would name some ("China Standard Time").
func FormatLocales ¶
func FormatLocales() []string
FormatLocales returns the locales of CLDR's modern coverage that this package has formatting data of, sorted: "af", "ar", "ar-AE"... A locale it lacks formats as the nearest of them, by Parent, or as English.
func FormatNumber ¶
func FormatNumber(locale string, n any, o NumberOptions) string
FormatNumber writes a number in the way of locale: its decimal and grouping separators, its grouping (the Indian 12,34,567 too, and none of four digits where the locale groups from five, as Spanish and Polish do), its minus and percent signs, and the digits of its default numbering system (Arabic-Indic in Persian, Bengali in Bengali; a locale with "-u-nu-latn" writes Latin digits). n is an integer of any Go type, a float32 or float64 (its fewest digits that read back as it, which are then rounded: 1.005 is "1.01" with two fraction digits, as Intl writes it), or a string of a decimal number, as "1234.5", exact however many digits it has.
NaN and infinities are the locale's symbols of them; a value that is not a number is written by fmt.
func HourCycle ¶
HourCycle returns how locale writes times, 12 for times with AM and PM and 24 for times without, by CLDR's time data for its region, or the one its extension names ("en-US-u-hc-h23").
func Languages ¶
func Languages() []string
Languages returns the languages of the catalogs the app registered, the source language of the first one first, or nil when it registered none.
func Locale ¶
func Locale() string
Locale returns the language the app shows, as the function SetLocaleFunc set returns it, or "" before it is set, which catalogs read as their source language.
func Match ¶
Match returns the language of supported that best suits a reader of preferred, the languages they read, most preferred first, or "" when none suits them. It returns the tag as supported spells it.
A supported language suits a reader when CLDR finds it close to one they read: another region of the same language and script, as en-GB for en-AU, pt-BR for pt-PT or es-ES for es-MX, or the language without a region. A language written in another script does not suit them: zh-Hans is no match for zh-TW, nor sr-Latn for sr-Cyrl. A match of a language they prefer more wins over a closer match of one they prefer less: fr for fr-CA wins over de for de.
func Months ¶
Months returns the names of the months in locale, January first, in a width. A name that stands alone, as a calendar's heading or a list of months, takes standAlone: some languages write it otherwise inside a date ("января" of "5 января" but "январь" alone, in Russian).
func Normalize ¶
Normalize returns locale as a BCP 47 tag in its canonical form, or "" when it names no language, as "C", "POSIX" or "". It reads BCP 47 tags in any case ("en-us" is "en-US"), POSIX locales ("zh_CN.UTF-8" is "zh-CN", "sr_RS@latin" is "sr-Latn-RS") and the old codes of a language ("iw" is "he", "in" is "id").
func Parent ¶
Parent returns the locale tag inherits what it lacks from, by the parent locales of CLDR, or "" when it is the root: "en-001" for "en-AU", "en" for "en-001", "zh-Hant-HK" for "zh-Hant-MO", "no" for "nb", and the tag without its last subtag otherwise ("de" for "de-CH"). A language written in a script other than its usual one inherits from nothing (CLDR's nonlikelyScript rule): the parent of "zh-Hant" or "sr-Latn" is the root, not "zh" or "sr", whose texts are in another script. Extensions, as "-u-ca-buddhist", are dropped first.
func Register ¶
func Register(c *Catalog)
Register adds an app's catalog to those the app ships, which the TypeScript and Go code `golet generate` writes for it does: its languages become the app's (Languages), and its keys "<namespace>.<key>" change the messages of libraries, as Golet's own. A library's catalog is not registered.
func SetLocaleFunc ¶
func SetLocaleFunc(f func() string)
SetLocaleFunc sets the function that returns the language the app shows, in which Locale, and so the functions `golet generate` writes, say their messages. Package golet sets it to its App.Locale; apps change the language with golet.App.SetLocale, not here. f must be safe to call from any goroutine.
Types ¶
type Arg ¶
Arg is an argument of a message: its name and its kind, "" for {name}, or "number", "date", "time", "plural", "selectordinal" or "select".
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
A Catalog holds the messages of an app, or of a library, in the languages it is translated to: a file of ARB-style JSON per language, named after its BCP 47 tag, "en.json", "zh-Hant.json", whose keys name messages of ICU MessageFormat (see Message):
{
"@@locale": "en",
"filesSelected": "{count, plural, one {# file selected} other {# files selected}}",
"@filesSelected": {
"description": "The status bar, while files are selected.",
"placeholders": {"count": {"type": "int"}}
}
}
A key starting with @ holds metadata, which only the file of the source language (the one the app is written in) needs. `golet generate` writes typed functions for the keys of an app's catalog, which register it (Register), so that an app rarely uses a Catalog itself.
A Catalog reads the file of a language when it first formats a message in it, and keeps it. It is safe for concurrent use.
func NewCatalog ¶
NewCatalog returns the catalog of the JSON files at the root of fsys, "<tag>.json", whose source language, the one its messages are written in first, is source: the language whose messages the others fall back to. Their names must be BCP 47 tags in their canonical form; their contents are read as they are needed. A message that does not parse, or a file that does not, is left out, and its keys fall back as missing ones do: `golet generate` and `golet i18n check` report them.
func NewLibraryCatalog ¶
NewLibraryCatalog returns the catalog of a library, as NewCatalog does, whose messages an app changes, or translates to other languages, with keys of its own catalogs named "<namespace>.<key>": Golet's own strings, those of its controls and menus, are a library's catalog whose namespace is "golet", and an app's de.json that says
"golet.cancel": "Abbrechen"
translates the controls' "cancel" to German.
A library's messages are said in the language the app shows (Locale), and fall back along its parents, then to the source language of the app, then to the library's. A library's catalog is not registered: the languages an app ships are its own.
func (*Catalog) Add ¶
Add adds the languages of the JSON files at the root of fsys, named as NewCatalog's, to the catalog: translations kept apart from it, as those of Golet's own strings are, each in a package an app imports for a language it ships. It fails on a language the catalog has already, and on files not named after a language; an app's registered catalog ships the languages it adds. Add is safe for concurrent use with formatting, which says the new languages from then on.
func (*Catalog) Format ¶
Format formats the message of key in locale with args (see Message.Format), or returns key when the catalog has no such message.
The message is the one of the catalog's language that best suits locale (Match), as "zh-Hant" for "zh-TW", or, when that language lacks it, of the language's parents (Parent), as "en-001" then "en" for "en-AU", else of the source language. Its cases follow the plural rules of the language it is in; numbers and dates, the conventions of locale. "" is the source language; the pseudo locales en-XA and ar-XB transform the source language's messages (IsPseudo).
A message formatted without arguments is kept, so that saying it again in the same locale costs a map lookup and allocates nothing.
Example ¶
c, _ := NewCatalog(fstest.MapFS{
"en.json": {Data: []byte(`{"files": "{n, plural, =0 {No files} one {# file} other {# files}}"}`)},
"de.json": {Data: []byte(`{"files": "{n, plural, =0 {Keine Dateien} one {# Datei} other {# Dateien}}"}`)},
}, "en")
fmt.Println(c.Format("en", "files", map[string]any{"n": 1}))
fmt.Println(c.Format("de-AT", "files", map[string]any{"n": 0}))
fmt.Println(c.Format("en-XA", "files", map[string]any{"n": 3}))
Output: 1 file Keine Dateien [3 ƒîļéš one]
func (*Catalog) Languages ¶
Languages returns the languages of the catalog: its source language, then the others, sorted.
func (*Catalog) Message ¶
Message returns the message of key that Format formats in locale, and the language it is in.
type DateFormatter ¶
type DateFormatter struct {
// contains filtered or unexported fields
}
A DateFormatter writes times in a locale with options, for writing many: FormatDate keeps one per locale and options.
func NewDateFormatter ¶
func NewDateFormatter(locale string, o DateOptions) *DateFormatter
NewDateFormatter returns the formatter of locale and o.
func (*DateFormatter) Pattern ¶
func (f *DateFormatter) Pattern() string
Pattern returns the pattern of CLDR the formatter writes, as "MMM d, y".
type DateOptions ¶
type DateOptions struct {
// Date and Time are the styles of the date and of the time.
Date, Time Style
// Skeleton names the fields to write when Date and Time are
// NoStyle, in CLDR's letters and any order: "yMMMd" (Jan 5, 2026),
// "yMMMM" (January 2026), "MMMd", "Ed" (5 Mon), "jm" (the hour and
// minute in the locale's hour cycle: 1:07 PM, 13:07), "Hm", "hms".
// The locale's pattern that suits it best is found as ICU's
// DateTimePatternGenerator finds it. Letters: y, M, L (a month
// standing alone), d, E (weekday), j, h, H, K, k, a, m, s, z. No
// style and no skeleton is "yMd". An hour letter other than j is that
// hour cycle (h 1 to 12, H 0 to 23, K 0 to 11, k 1 to 24), as V8
// reads Intl's hourCycle. EEEEEE, CLDR's short weekday ("Mo"), has no
// option of Intl: pages write the abbreviated one ("Mon") in its place.
Skeleton string
// HourCycle is 12 or 24 to write times so whatever the locale's
// hours, as the user's regional settings say (Region.HourCycle); 0
// keeps the locale's, or the one its extension names ("-u-hc-h23").
HourCycle int
}
DateOptions are how FormatDate writes a time: its date, its time or both by style, as Intl.DateTimeFormat's dateStyle and timeStyle, or the fields of a skeleton, as its other options.
type Dir ¶
type Dir uint8
Dir is the direction a language is written in.
func Direction ¶
Direction returns the direction tag is written in, that of its script: right to left for Arabic, Hebrew and the other scripts written so, where a tag names no script, the one its language is most likely written in (ar is Arab, ar-XB, the pseudo locale, too). A tag that names no language is left to right.
type Message ¶
type Message struct {
// contains filtered or unexported fields
}
A Message is a message of ICU MessageFormat, parsed: text with arguments that the values given to Format replace, as ARB files and Flutter's gen_l10n write them:
Hello, {name}!
{count, plural, =0 {No files} one {# file} other {# files}}
{count, plural, offset:1 =0 {Nobody} =1 {{host}} one {{host} and # other} other {{host} and # others}}
{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}
{gender, select, female {She} male {He} other {They}} replied.
{price, number} on {day, date, short} at {day, time, short}
An argument {name} writes the value of name, a number formatted for the locale (as {name, number} does) and a time.Time as a short date and time. A plural argument picks the case of the number's plural category in the language (one, few, other...), or of an exact value, =0; # in its cases writes the number less the offset. A select argument picks the case that is the value, as a string, or other; every plural and select argument has an other case. Cases nest.
An apostrophe quotes, as ICU's does: '{' writes a brace, '#' a #, '{a}' the text {a}, and two apostrophes write one. An apostrophe before any other character is one: "don't" needs no quoting.
func MustParseMessage ¶
MustParseMessage is ParseMessage, but panics when s is not a message.
func ParseMessage ¶
ParseMessage parses a message of ICU MessageFormat.
func (*Message) Args ¶
Args returns the arguments of the message, nested ones too, in the order they come; an argument used twice comes once, with its first kind other than "".
func (*Message) Cases ¶
Cases returns the keys of the cases of the plural, selectordinal or select arguments named name, as "=0", "one" and "other", in the order they come, each once.
func (*Message) Format ¶
Format writes the message with args, the values of its arguments by name, for locale: the language whose plural rules pick the cases of plural and selectordinal arguments, and whose conventions numbers and dates follow. An argument args lacks is written as it is in the message, {name}. The pseudo locales (IsPseudo) transform the message, which keeps the plural rules of English.
Values: a string, an integer or floating-point number, a string of a decimal number (which keeps its fraction digits: "1.50"), a bool, a time.Time, an error, a fmt.Stringer, or anything fmt.Sprint writes.
type NumberFormatter ¶
type NumberFormatter struct {
// contains filtered or unexported fields
}
A NumberFormatter writes numbers in a locale with options, for writing many: FormatNumber keeps one per locale and options.
func NewNumberFormatter ¶
func NewNumberFormatter(locale string, o NumberOptions) *NumberFormatter
NewNumberFormatter returns the formatter of locale and o.
func (*NumberFormatter) Format ¶
func (f *NumberFormatter) Format(n any) string
Format writes n (see FormatNumber).
type NumberOptions ¶
type NumberOptions struct {
// Percent writes the number times 100, with the locale's percent sign
// where its pattern puts it: 0.25 is "25%" in English, "25 %" in
// German, "%25" in Turkish. Percents have no fraction digits unless
// MaxFractionDigits says otherwise.
Percent bool
// Integer rounds to a whole number, as MaxFractionDigits 0 would.
Integer bool
// MinFractionDigits and MaxFractionDigits bound the digits after the
// decimal separator: 1.5 with MinFractionDigits 2 is "1.50", 1.2345
// with MaxFractionDigits 2 is "1.23". MaxFractionDigits 0 is the
// style's default (3, none for percents), or MinFractionDigits when
// that is more.
MinFractionDigits, MaxFractionDigits int
// MinIntegerDigits pads the integer part with zeros to as many
// digits: 7 with 2 is "07".
MinIntegerDigits int
// NoGrouping leaves out the separators of thousands: "12345".
NoGrouping bool
// HalfEven rounds a number halfway between two to the even one, as
// ICU's MessageFormat does ("2.5" is "2"), rather than away from zero
// ("3"), as Intl.NumberFormat does.
HalfEven bool
}
NumberOptions are how FormatNumber writes a number. The zero value writes it as Intl.NumberFormat does by default: grouped, with up to three fraction digits, rounded half away from zero.
type Operands ¶
type Operands struct {
// I is the integer digits: 3 for 3.25.
I uint64
// V and W are the numbers of visible fraction digits, with trailing
// zeros and without: 2 and 1 for 1.50.
V, W int
// F and T are the visible fraction digits as an integer, with trailing
// zeros and without: 50 and 5 for 1.50.
F, T uint64
// C is the exponent of compact decimal notation, as 6 for "1.2M"
// written 1.2c6, whose integer digits are then those of 1200000.
C int
}
Operands are the operands of a number that the plural rules of CLDR read (Unicode Technical Standard #35, Part 3, Plural Operand Meanings), of its absolute value as it is written: 1.50 has two visible fraction digits that 1.5 does not have, and in some languages another plural.
An integer part or a fraction of more than 18 digits keeps its last 18, plus 10^18, so that it equals no number of the rules, which are smaller, and its remainders by the powers of ten the rules divide by stay right.
func NewOperands ¶
NewOperands returns the operands of n: an integer of any Go type, a float32 or float64 as strconv writes it in the fewest digits (1.5, never 1.50), a string of a decimal number, which keeps the fraction digits it writes ("1.50", "-3", "1.2c6" or "1.2e6" in CLDR's compact notation), or Operands. A minus sign is ignored.
type Plural ¶
type Plural uint8
Plural is a plural category of the Unicode CLDR: the form of a word or a phrase a language uses for a number. English has two for cardinal numbers, "1 file" (One) and "2 files" (Other), and four for ordinal ones, "1st", "2nd", "3rd" and "4th"; Japanese has one, Arabic six.
func OrdinalCategories ¶
OrdinalCategories returns the categories of ordinal numbers in the language of tag: [PluralOne PluralTwo PluralFew PluralOther] for English.
func OrdinalCategory ¶
OrdinalCategory returns the plural category of an ordinal number in the language of tag, as "1st" and "2nd": the place of something in a row.
func ParsePlural ¶
ParsePlural returns the category a keyword names, as "few", and whether it names one.
func PluralCategories ¶
PluralCategories returns the categories of cardinal numbers in the language of tag, in the order of Plural: [PluralOne PluralOther] for English.
func PluralCategory ¶
PluralCategory returns the plural category of a cardinal number in the language of tag, as "1 file" and "2 files": the number of something. The rules are those of CLDR for the language, or for the language without its region and script when CLDR has none of its own (pt-PT has its own, pt-BR is pt's); a language CLDR has no rules for has the one category Other.
type Region ¶
type Region struct {
// Locale is the locale of the formats, a BCP 47 tag such as "en-GB"
// or "de-DE", or "" when the system names none.
Locale string
// FirstWeekday is the day calendars start their weeks on.
FirstWeekday time.Weekday
// HourCycle is 12 for times with AM and PM, 24 for times without, or
// 0 when it is not known, which the zero Region is: its first weekday,
// Sunday, means nothing then.
HourCycle int
}
Region is how a reader writes dates, times and numbers: the regional formats of their system, with the changes they made to them, which may be those of another language than the one they read, as an English reader in Germany who wants weeks to start on Monday and the time in 24 hours. Golet's App.Region reports it, and native UI reads it with Context.Region.
func RegionFor ¶
RegionFor returns the regional formats CLDR gives locale: the first day of the week and the hour cycle of its region. The system's settings, which golet.App.Region reports, may differ.
func (Region) FormatLocale ¶
FormatLocale returns the locale a reader of lang with these regional formats writes numbers and dates in, as Apple's Locale.current puts the two together: the language with the region of the formats, and their first weekday and hour cycle as the keys of its Unicode extension, as "en-GB-u-fw-mon-hc-h23" for English read with British formats, or "en-DE-u-fw-mon-hc-h23" with German ones. Without a locale of formats it is lang's, with its first weekday and hour cycle when set. The pseudo locales (IsPseudo) write them in English, as the formatting of package i18n reads them.
type Style ¶
type Style uint8
Style is the length of a date or a time as CLDR writes them by style.
const ( // NoStyle leaves the date, or the time, out. NoStyle Style = iota // ShortStyle is numeric: "1/5/26", "1:07 PM". ShortStyle // MediumStyle abbreviates: "Jan 5, 2026", "1:07:09 PM". MediumStyle // LongStyle writes the month out: "January 5, 2026", "1:07:09 PM UTC". LongStyle // FullStyle writes everything: "Monday, January 5, 2026", // "1:07:09 PM Coordinated Universal Time". FullStyle )
type SyntaxError ¶
type SyntaxError struct {
Message string // the message
Offset int // the byte offset in it of the error
Err string
}
SyntaxError is the error of a message that does not parse.
func (*SyntaxError) Error ¶
func (e *SyntaxError) Error() string
type Width ¶
type Width uint8
Width is the width of the names of months, weekdays and day periods.
const ( // Wide names are whole: "January", "Monday". Wide Width = iota // Abbreviated names are short: "Jan", "Mon". Abbreviated // Short names are shorter still, for weekdays only: "Mo"; months // have abbreviated names in their place. Short // Narrow names are a letter or so: "J", "M", for calendars. Narrow )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
gen
command
Command gen writes the data of the Unicode CLDR that package i18n uses, from a pinned release of cldr-json, as Go source: `go generate ./i18n` runs it.
|
Command gen writes the data of the Unicode CLDR that package i18n uses, from a pinned release of cldr-json, as Go source: `go generate ./i18n` runs it. |