i18n

package
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package i18n is Silk's translation runtime — the equivalent of Qt's QTranslator + tr() pair. Source strings stay in Go code (so grep finds them, IDE refactors them, and the binary runs without any translation file at all). At runtime the translator looks up the source string in a per-locale map and returns the translated form. On a lookup miss it returns the source string unchanged, so a missing translation never produces a blank UI.

Typical usage:

import "github.com/uk0/silk/i18n"

func init() {
    i18n.LoadFromFile("translations/zh-CN.json")
    i18n.SetLocale("zh-CN")
}

label := gui.NewLabel(i18n.T("File"))           // "文件"
status := i18n.Tf("Saved %s", filename)         // "已保存 main.go"
hint := i18n.Tn("%d item", "%d items", count)   // pluralized

Goal lined up against Qt: Qt's tr() depends on the MOC compiler to embed source strings into a .ts file. Silk has no MOC and we don't want one — instead the translator just keys off the source string at runtime. xgettext-style tooling can scan source for i18n.T(...) calls and emit a starter translation table; we leave that to a future tool.

File format: JSON, mapping locale → key → translated string. A real-world translations.json:

{
  "zh-CN": { "File": "文件", "Edit": "编辑" },
  "ja":    { "File": "ファイル" }
}

Plurals: per-locale plural function maps integer count to a plural-form index. Two simple builtin rules cover most needs: English-like (1 / other) and Chinese-like (no plurals). Custom languages register their own via Translator.SetPluralRule.

Index

Constants

This section is empty.

Variables

View Source
var Default = NewTranslator()

Default is the singleton used by package-level helpers. Replace at startup if you need a custom configuration shared by all callers.

Functions

func Add

func Add(locale, source, translated string)

Add registers a single (locale, source, translated) entry on Default.

func AddMany

func AddMany(locale string, translations map[string]string)

AddMany merges a whole locale into Default. Convenience for tests and small embedded translation tables.

func DetectLocale

func DetectLocale() (string, error)

DetectLocale returns the host's preferred locale, in priority order:

  1. LC_ALL — POSIX override, beats every other env var.
  2. LC_MESSAGES — POSIX message-catalog locale (the closest analogue of the i18n.T target).
  3. LANG — POSIX user-default locale.

On macOS, we additionally consult `defaults read -g AppleLocale` because the env vars there are typically empty unless the user is running from a properly-configured shell. The macOS check is best- effort; failure surfaces as the env-var fallback below.

Returns ("en", nil) when nothing is set — a sensible neutral default rather than "" so callers can pass the result straight to SetLocale and start translating.

func LoadFromBytes

func LoadFromBytes(data []byte) error

LoadFromBytes calls Default.LoadFromBytes.

func LoadFromFile

func LoadFromFile(path string) error

LoadFromFile calls Default.LoadFromFile.

func Locale

func Locale() string

Locale returns Default.Locale.

func SetLocale

func SetLocale(locale string)

SetLocale calls Default.SetLocale.

func T

func T(source string) string

T calls Default.T.

func Tf

func Tf(source string, args ...interface{}) string

Tf calls Default.Tf.

func Tn

func Tn(source, plural string, n int) string

Tn calls Default.Tn.

func TnEx

func TnEx(forms []string, n int) string

TnEx calls Default.TnEx.

Types

type PluralRule

type PluralRule func(n int) int

PluralRule maps an integer count to a plural-form index. Index 0 is always the first form supplied to Tn; subsequent forms (index 1..) are passed via the variadic plurals slice on extended APIs (TnEx).

The rule is a function so locales with non-trivial rules — Russian has 3 forms, Arabic has 6 — can be expressed without committing the package to a specific data format.

type Translator

type Translator struct {
	// contains filtered or unexported fields
}

Translator holds a per-locale translation table and is the unit of translation in this package. The package-level helpers (T, Tn, Tf, SetLocale, LoadFromFile, ...) all delegate to a global Default translator; tests and multi-tenant runtimes can construct their own via NewTranslator.

Synchronisation: every Translator is internally locked with a RWMutex so callers from goroutines other than the UI thread see a consistent view. Reads (T/Tf/Tn) are concurrent; writes (SetLocale, Load*) are serialised. The lock cost is negligible compared to the map lookup.

func NewTranslator

func NewTranslator() *Translator

NewTranslator creates an empty translator with no locale and no loaded translations. Callers populate via Load*, then activate a locale with SetLocale.

func (*Translator) Add

func (t *Translator) Add(locale, source, translated string)

Add inserts a single translation entry. Useful for tests or for programmatically-built translation tables — production code usually loads a whole locale via Load*. Overwrites any existing entry for the same (locale, source) pair.

func (*Translator) AddMany

func (t *Translator) AddMany(locale string, translations map[string]string)

AddMany merges every entry from translations into the table for locale. Existing entries with the same key are overwritten. Used by the JSON loader to install a whole locale at once.

func (*Translator) Export

func (t *Translator) Export() map[string]map[string]string

Export returns the full translation table as a JSON-marshalable map, useful for tooling that wants to round-trip translations through memory or merge programmatic edits with file contents.

func (*Translator) LoadFromBytes

func (t *Translator) LoadFromBytes(data []byte) error

LoadFromBytes parses raw JSON content as a translation table and installs every locale into t. The expected shape is a single JSON object whose top-level keys are locale tags ("zh-CN", "en") and whose values are objects mapping source strings to translations.

{
  "zh-CN": { "File": "文件", "Edit": "编辑" },
  "ja":    { "File": "ファイル" }
}

Existing entries with the same (locale, key) pair are overwritten. Locales not in the file are unaffected.

func (*Translator) LoadFromFile

func (t *Translator) LoadFromFile(path string) error

LoadFromFile is LoadFromBytes that reads a file from disk first. The file is expected to be JSON encoded in UTF-8 (no BOM); other encodings need to be normalised by the caller.

func (*Translator) Locale

func (t *Translator) Locale() string

Locale returns the active locale tag, or "" when translation is off.

func (*Translator) SaveToFile

func (t *Translator) SaveToFile(path string) error

SaveToFile writes Export's result to path as pretty-printed JSON. Useful in tooling that programmatically edits translations and wants to persist them. Production translation files are usually edited by humans, so this exists for tests and helpers, not as the primary authoring path.

func (*Translator) SetLocale

func (t *Translator) SetLocale(locale string)

SetLocale activates a locale by tag (e.g. "zh-CN", "en-US", "ja"). Lookup misses fall back to the language root ("zh-CN" → "zh") and finally to the source string. An empty string disables translation.

func (*Translator) SetPluralRule

func (t *Translator) SetPluralRule(locale string, rule PluralRule)

SetPluralRule registers a custom pluralization rule for a locale or language root. "ru" applies to all Russian variants ("ru", "ru-RU"), "ru-RU" is more specific. Lookup picks the most specific match.

func (*Translator) T

func (t *Translator) T(source string) string

T returns the translation of source for the active locale, or source itself when no translation is registered. Argumentless — callers needing parameter substitution use Tf.

func (*Translator) Tf

func (t *Translator) Tf(source string, args ...interface{}) string

Tf is T with format substitution. The translated form is the fmt.Sprintf format string, so translators can reorder %s arguments for syntactic correctness in their language. Format directives must match in count and type across locales — verifying that is the translator's job, not the runtime's.

func (*Translator) Tn

func (t *Translator) Tn(source, plural string, n int) string

Tn picks between singular and plural forms based on n. Pass the English-style singular as source and plural as plural; both are looked up independently in the translation table. Languages with more than two forms call TnEx with the full list.

The returned string has %d substituted by n. To embed n with a specific format directive, write that directive in source/plural (e.g. "%d items", "%5d items"); we just feed n to fmt.Sprintf.

func (*Translator) TnEx

func (t *Translator) TnEx(forms []string, n int) string

TnEx is the multi-form Tn for languages like Russian or Arabic that have 3+ plural forms. forms is indexed by the locale's PluralRule output; the source-language singular at index 0 is also the lookup key into the translation table for every form.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL